<script setup name="customer">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import AddForm from './add.vue'
import EditForm from './edit.vue'
import Examine from './examine.vue'
import ContractUp from './contractUp.vue'
import LookForm from './look.vue'
import ContracExamine from './contracExamine.vue'
import auditHistory from './auditHistory.vue'
import {
  GetListAPI,
  AddDataAPI,
  EditDataAPI,
  DelDataAPI,
  GetDetailAPI,
  UploadContractAPI,
  CloseAPI,
  RevokeAPI,
  ToExamineAPI,
  ContractExamineAPI,
  ReviewSubmitAPI,
  DelDatasAPI
} from '@/api/order/subcontracting/order'
const { proxy } = getCurrentInstance()

const router = useRouter()
// 封装 方法 字典查询
const {
  customer_level, // 等级
  customer_affiliated_organization, //所属机构
  subcontracting_order_status //单据状态
} = proxy.useDict('customer_level', 'customer_affiliated_organization', 'subcontracting_order_status')

const FormRef = ref(null)

// 新增弹窗状态
const addIsShow = ref(false)

// 审核弹窗状态
const examineIsShow = ref(false)

// 合同审核
const contracExamineShow = ref(false)

// 查看
const lookShow = ref(false)
// 标题
const title = ref('新增')

// 保存加载状态
const Btnloading = ref(false)

// 表格加载状态
const loading = ref(false)

// 表格数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 是否禁用删除
const DelDisabled = ref(false)

// 是否禁用 单选
const examineDisabled = ref(false)

// 关结状态
const closingShow = ref(false)

//关结id
const closingId = ref()
const Ids = ref([])
const rows = ref([])
let id = ''
// 查询条件
const SelectList = ref([
  { type: '日期范围' },
  { label: '委外订单号', model: 'subcontractingOrderNum', type: '输入框', placeholder: '请输入委外订单号' },
  { label: '物料编码', model: 'materialCode', type: '输入框', placeholder: '请输入物料编码' },
  { label: '加工商名称', model: 'customerName', type: '输入框', placeholder: '请输入加工商名称' },
  { label: '关联单号', model: 'associatedDocNum', type: '输入框', placeholder: '请输入关联单号' },
  {
    label: '单据状态',
    model: 'status',
    type: '下拉单选',
    placeholder: '请输入加单据状态',
    opt: subcontracting_order_status
  }
])

// 新增字段
const ruleForm = ref({})

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 50
})

/**
 * 弹窗
 */
const add = () => {
  title.value = '新增'
  addIsShow.value = true
}

const edit = async id => {
  // console.log(id, 'id')
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '修改'
    const res = await GetDetailAPI(id)
    // console.log(res, 'res')
    ruleForm.value = res.data
    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 审核
const examine = async () => {
  if (rows.value[0].status != 2 && rows.value[0].status != 3)
    return proxy.warningMsg('此操作仅为待审核和审核中状态可用')
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '订单审核'
    const res = await GetDetailAPI(rows.value[0].id)
    ruleForm.value = res.data

    // 审核弹窗
    examineIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 合同审核
const contractExamine = async () => {
  const Obj = rows.value[0]
  if (!(Obj.status == 9 || Obj.status == 10)) return proxy.warningMsg('此操作仅为合同审核中和合同待审核状态可用')
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '合同审核'
    const res = await GetDetailAPI(Obj.id)
    ruleForm.value = res.data
    contracExamineShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}
//  合同上传 弹窗
const contractUp = async () => {
  const Obj = rows.value[0]
  if (Obj.status != 7 && Obj.status != 11) return proxy.warningMsg('此操作仅为待签订和合同未通过状态可用')
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '合同上传'
    const res = await GetDetailAPI(Obj.id)
    ruleForm.value = res.data

    addIsShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 查看
const dxamine = async val => {
  try {
    proxy.$modal.loading('请稍候...')
    title.value = '查看'
    const res = await GetDetailAPI(val.id)
    ruleForm.value = res.data
    rows.value = res.data
    lookShow.value = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  rows.value = selection
  Ids.value = selection.map(item => item.id)
  DelDisabled.value = !selection.length
  selection.length <= 0 || selection.length > 1 ? (examineDisabled.value = true) : (examineDisabled.value = false)
}
handleSelectionChange([])

// 新增
const addSub = async () => {
  const isif = await FormRef.value.submit()
  if (!isif) return
  // console.log('a')
  try {
    // console.log(isif)
    Btnloading.value = true
    await AddDataAPI(isif)
    addClose()
    getList()
    proxy.successMsg('新增成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 修改
const editSub = async () => {
  try {
    const isif = await FormRef.value.submit()
    if (!isif) return
    Btnloading.value = true
    const res = await EditDataAPI(isif)
    addClose()
    getList()
    proxy.successMsg('修改成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 审核同意
const yes = () => {}

// 审核不同意
const no = () => {}

// 合同提交后台
const contractSub = async () => {
  try {
    const isif = await FormRef.value.submit()
    if (!isif) return
    // console.log(isif)
    Btnloading.value = true
    await UploadContractAPI(isif)
    proxy.successMsg('上传成功')
    addClose()
    getList()
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 提交审核
const subExamine = async () => {
  const is = rows.value.every(t => ['1'].includes(t.status))
  if (!is) return proxy.warningMsg('只有待提交的数据可操作!')
  const MesBox = await proxy.FreezMessageBox('是否确定提交审核？')
  if (!MesBox) return
  await ReviewSubmitAPI({ idStr: Ids.value.join(',') })
  proxy.successMsg('操作成功')
  getList()
}

// 撤销审核
const revoke = async () => {
  const Obj = rows.value[0]
  if (Obj.status != 2) return proxy.warningMsg('此操作仅为待审核状态可用')
  const MesBox = await proxy.FreezMessageBox('是否确定撤销审核？')
  if (!MesBox) return
  const res = await RevokeAPI(Ids.value[0])
  if (res.code !== 200) return
  proxy.successMsg('撤销成功')
  getList()
}

// 关结弹窗
const closing = val => {
  id = val ? val : Ids.value[0]
  closingShow.value = true
  closingId.value = val ? val : Ids.value[0]
}

// 关结
const closingSub = async val => {
  const Obj = {
    closeReason: val.closeReason,
    id
  }
  const res = await CloseAPI(Obj)
  if (res.code !== 200) return
  closingShow.value = false
  proxy.successMsg('关结成功')
  getList()
}

/**
 * 批量审核
 */
const allExamine = async () => {
  const is = rows.value.every(t => ['2', '3'].includes(t.status))
  if (!is) return proxy.warningMsg('只有待审核和审核中的数据可操作!')
  const num = rows.value.length
  const MesBox = await proxy.FreezMessageBox1(`共${num}条审核订单`)
  if (MesBox) {
    await ToExamineAPI({
      idStr: Ids.value.join(','),
      isAdopt: '1'
    })
    getList()
  } else {
    await ToExamineAPI({
      idStr: Ids.value.join(','),
      isAdopt: '2'
    })
    getList()
  }
}

// 合同审核  || 不同意  （同意1 不同意 2)
const contracExamine = async val => {
  try {
    proxy.$modal.loading('审核中,请稍后')

    const isif = await FormRef.value.submit()
    if (!isif) return
    Btnloading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      idStr: Ids.value[0],
      isAdopt: val
    }
    await ContractExamineAPI(form)
    contracExamineShow.value = false
    getList()
    proxy.successMsg('操作成功')
  } catch {
  } finally {
    Btnloading.value = false
    proxy.$modal.closeLoading()
  }
}

// 审核同意 || 不同意  （同意1 不同意 2
const yesAndNo = async val => {
  const isif = await FormRef.value.submit()
  if (!isif) return
  try {
    Btnloading.value = true
    const form = {
      reviewComments: isif.reviewComments,
      idStr: Ids.value.join(','),
      isAdopt: val
    }
    await ToExamineAPI(form)
    examineIsShow.value = false
    getList()
    proxy.successMsg('操作成功')
  } catch {
  } finally {
    Btnloading.value = false
  }
}

// 新增修改弹窗关闭时
const addClose = () => {
  addIsShow.value = false
  ruleForm.value = {}
  getList()
}

// 新增修改弹窗关闭时
const examineClose = () => {
  examineIsShow.value = false
  contracExamineShow.value = false
  lookShow.value = false
  ruleForm.value = {}
  getList()
}

// 删除
const remove = async () => {
  try {
    const isif = await proxy.DelMessageBox()
    if (!isif) return
    proxy.$modal.loading('删除中,请稍后')
    await DelDatasAPI(Ids.value.join(','))
    proxy.successMsg('操作成功')
    getList()
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 条件查询
const selectSubmit = Obj => {
  for (let KEY in Obj) {
    query[KEY] = Obj[KEY]
  }
  getList()
}

// 获取列表
const getList = async () => {
  loading.value = true
  try {
    const res = await GetListAPI(query)
    TableData.value = res.rows
    total.value = res.total
  } catch (error) {
    loading.value = false
  } finally {
    loading.value = false
  }
}
getList()

const tableHeight = ref(0)

const maxHeight = computed(() => {
  const windowHeight = window.innerHeight
  const headerHeight = 310
  const paginationHeight = 0
  return windowHeight - headerHeight - paginationHeight
})

const handleResize = () => {
  tableHeight.value = maxHeight.value
}

onMounted(() => {
  tableHeight.value = maxHeight.value
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
})
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <el-button type="primary" v-hasPermi="['order:subcontracting:order:add']" @click="add">添加</el-button>
      <el-button
        type="warning"
        v-hasPermi="['order:subcontracting:order:submitReview']"
        :disabled="DelDisabled"
        @click="subExamine"
        >提交审核</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:subcontracting:order:review']"
        :disabled="DelDisabled"
        @click="allExamine"
        >批量审核</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:subcontracting:order:review']"
        :disabled="examineDisabled"
        @click="examine"
        >订单审核</el-button
      >
      <!-- <el-button
        type="primary"
        v-hasPermi="['order:subcontracting:order:uploadContract']"
        :disabled="examineDisabled"
        @click="contractUp"
        >合同上传</el-button
      >
      <el-button
        type="warning"
        v-hasPermi="['order:subcontracting:order:contractReview']"
        :disabled="examineDisabled"
        @click="contractExamine"
        >合同审核</el-button
      > -->
      <el-button
        type="primary"
        v-hasPermi="['order:subcontracting:order:deleteReview']"
        :disabled="examineDisabled"
        @click="revoke"
        >撤销审核</el-button
      >
      <el-button
        type="success"
        v-hasPermi="['order:subcontracting:order:close']"
        :disabled="examineDisabled"
        @click="closing(false)"
        >关结</el-button
      >
      <el-button
        type="danger"
        v-hasPermi="['order:subcontracting:order:remove']"
        :disabled="DelDisabled"
        @click="remove(false)"
        >删除</el-button
      >
      <!-- <el-button type="info" @click="importFn">导入</el-button>
      <el-button type="info" @click="exportFn">导出</el-button> -->
      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        stripe
        border
        :data="TableData"
        class="tableClass"
        @selection-change="handleSelectionChange"
        :height="maxHeight"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="单据日期" prop="createTime" width="150" />

        <el-table-column label="委外订单号" align="center" :show-overflow-tooltip="true" width="150">
          <template #default="scope">
            <el-link type="primary" @click="router.push('/order/subcontracting/order-data?id=' + scope.row.id)">{{
              scope.row.subcontractingOrderNum
            }}</el-link>
          </template>
        </el-table-column>

        <el-table-column label="单据状态" align="center" width="120">
          <template #default="scope">
            <p-tag bgc="#006cb6" text="待提交" v-if="scope.row.status == 1" />
            <p-tag bgc="#fbc82f" text="待审核" v-else-if="scope.row.status == 2" />
            <p-tag bgc="#f28e16" text="审核中" v-else-if="scope.row.status == 3" />
            <p-tag bgc="#ff0000" text="订单未通过" v-else-if="scope.row.status == 4" />
            <p-tag bgc="#bebebe" text="已完成" v-else-if="scope.row.status == 5" />
            <p-tag bgc="#9a9a9a" text="已关结" v-else-if="scope.row.status == 6" />
            <p-tag bgc="#8e7cc3" text="待签订" v-else-if="scope.row.status == 7" />
            <p-tag bgc="#36a0da" text="待到货" v-else-if="scope.row.status == 8" />
            <p-tag bgc="#fbc82f" text="待合同审核" v-else-if="scope.row.status == 9" />
            <p-tag bgc="#f28e16" text="合同审核中" v-else-if="scope.row.status == 10" />
            <p-tag bgc="#ff0000" text="合同未通过" v-else />
          </template>
        </el-table-column>
        <el-table-column label="物料编码" prop="materialCode" width="150" />
        <el-table-column label="物料名称" prop="materialName" width="150" />
        <el-table-column label="规格型号" prop="specType" width="150" />
        <el-table-column label="供应商名称" prop="supplierName" width="150" />
        <el-table-column label="加工商" prop="converterDict" width="150" />
        <el-table-column label="加工单价" prop="machiningPrice" width="150" />
        <el-table-column label="委外数量" prop="subcontractingWeight" width="120" />
        <el-table-column label="点数" prop="pointPosition" width="120" />
        <el-table-column label="到货数量" prop="arrivedWeight" width="120" />
        <el-table-column label="开单人" prop="createBy" width="120" />
        <el-table-column label="计划开工日期" prop="estimatedStartTime" width="120" />
        <el-table-column label="计划完工日期" prop="estimatedEndTime" width="180" />
        <el-table-column label="单据备注" prop="remark" width="220" />
        <el-table-column label="操作" align="center" width="160" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                text="修改"
                v-hasPermi="['order:subcontracting:order:edit']"
                v-show="scope.row.status == 1 || scope.row.status == 4"
                @click="edit(scope.row.id)"
              />
              <el-link
                type="primary"
                v-hasPermi="['order:subcontracting:order:close']"
                v-show="scope.row.status == 1 || scope.row.status == 4 || scope.row.status == 11"
                text="关结"
                @click="closing(scope.row.id)"
              />
              <el-link type="primary" text="查看" @click="dxamine(scope.row)" />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="addIsShow" :title="title" @close="addClose" width="60%">
      <template #body>
        <AddForm ref="FormRef" v-if="title == '新增'" />
        <EditForm ref="FormRef" :data="ruleForm" v-if="title == '修改'" />

        <!-- 上传合同 -->
        <ContractUp ref="FormRef" :data="ruleForm" v-if="title == '合同上传'" />
        <div style="width: 100%" v-if="title != '查看'">
          <div class="Btn" v-if="title !== '查看'">
            <el-button
              type="primary"
              v-if="title == '新增' || title == '修改'"
              :loading="Btnloading"
              @click="title == '新增' ? addSub() : editSub()"
              >保存</el-button
            >
            <el-button type="primary" v-if="title == '合同上传'" :loading="Btnloading" @click="contractSub"
              >保存</el-button
            >
            <el-button type="inof" @click="addClose">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 审核弹窗 -->
    <p-XiaoheDialog :dialogVisible="examineIsShow" title="审核" @close="examineClose" width="60%">
      <template #body>
        <auditHistory
          perms="order:subcontracting:order:review"
          :title="title == '查看' ? '基本信息' : '审核'"
          :auditDoc="ruleForm.subcontractingOrderNum"
        >
          <template #body>
            <Examine :data="ruleForm" ref="FormRef" />
          </template>
        </auditHistory>
        <div style="width: 100%">
          <div class="Btn">
            <el-button type="danger" :loading="Btnloading" @click="yesAndNo(2)">不同意</el-button>
            <el-button type="success" :loading="Btnloading" @click="yesAndNo(1)">同意</el-button>
            <el-button type="inof" @click="examineClose">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 合同审核 -->
    <p-XiaoheDialog :dialogVisible="contracExamineShow" title="合同审核" @close="examineClose" width="60%">
      <template #body>
        <auditHistory perms="order:subcontracting:order:contractReview" :auditDoc="ruleForm.subcontractingContractNum">
          <template #body>
            <ContracExamine ref="FormRef" :data="ruleForm" />
          </template>
        </auditHistory>
        <div style="width: 100%">
          <div class="Btn">
            <el-button type="danger" :loading="Btnloading" @click="contracExamine(2)">不同意</el-button>
            <el-button type="success" :loading="Btnloading" @click="contracExamine(1)">同意</el-button>
            <el-button type="inof" @click="examineClose">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 查看 -->
    <p-XiaoheDialog :dialogVisible="lookShow" title="查看" @close="examineClose" width="60%">
      <template #body>
        <auditHistory :auditDoc="ruleForm">
          <template #body>
            <LookForm ref="FormRef" :data="ruleForm" />
          </template>
        </auditHistory>
      </template>
    </p-XiaoheDialog>
    <!-- 关结原因 -->
    <Closing :id="closingId" :isShow="closingShow" @submit="closingSub" @close="closingShow = false" />
  </div>
</template>

<style scoped lang="scss"></style>
